<template>
  <div class="order-tab">
    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ getCurrencySymbol(primaryCurrency) }}{{ totalAmount }}</div>
              <div class="stat-label">总消费金额</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Discount /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ getCurrencySymbol(primaryCurrency) }}{{ totalDiscount }}</div>
              <div class="stat-label">总优惠金额</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ getCurrencySymbol(primaryCurrency) }}{{ averageOrder }}</div>
              <div class="stat-label">平均订单金额</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="16" align="middle">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号或商品名称"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="timeRange" placeholder="时间范围" size="small" clearable>
            <el-option label="全部时间" value="" />
            <el-option label="最近7天" value="7" />
            <el-option label="最近30天" value="30" />
            <el-option label="最近90天" value="90" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="orderStatus" placeholder="订单状态" size="small" clearable>
            <el-option label="全部状态" value="" />
            <el-option label="已完成" value="completed" />
            <el-option label="进行中" value="processing" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="exportOrders">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 订单列表 -->
    <div class="orders-section">
      <el-table 
        :data="filteredOrders" 
        border 
        stripe 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        row-class-name="order-row"
      >
        <el-table-column prop="id" label="订单号" width="140">
          <template #default="scope">
            <div class="order-id">
              <el-tag size="small" type="info">{{ scope.row.id }}</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="商品信息" min-width="200">
          <template #default="scope">
            <div class="product-info">
              <div class="product-name">{{ scope.row.name }}</div>
              <div class="product-meta">
                <span class="quantity">数量: {{ scope.row.count }}</span>
                <span class="price">单价: {{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.price }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="费用明细" min-width="300">
          <template #default="scope">
            <div class="fee-details">
              <div class="fee-row">
                <span class="fee-label">手续费:</span>
                <span class="fee-value">{{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.fee }}</span>
              </div>
              <div class="fee-row">
                <span class="fee-label">附加费:</span>
                <span class="fee-value">{{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.extra }}</span>
              </div>
              <div class="fee-row">
                <span class="fee-label">运费补差:</span>
                <span class="fee-value">{{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.freight }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="优惠信息" min-width="200">
          <template #default="scope">
            <div class="discount-info">
              <div class="discount-row" v-if="scope.row.coupon">
                <el-tag size="small" type="success">优惠券</el-tag>
                <span class="discount-value">-{{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.coupon }}</span>
              </div>
              <div class="discount-row" v-if="scope.row.point">
                <el-tag size="small" type="warning">积分抵扣</el-tag>
                <span class="discount-value">-{{ getCurrencySymbol(scope.row.currency) }}{{ scope.row.point }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="rate" label="汇率" width="80">
          <template #default="scope">
            <span class="rate-value">{{ scope.row.rate }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="pay" label="实付金额" width="120">
          <template #default="scope">
            <div class="pay-amount">
              <div class="amount-main">{{ getCurrencySymbol(scope.row.currency) }}{{ formatPayAmount(scope.row.pay) }}</div>
              <div class="amount-sub" v-if="scope.row.currency === 'JPY'">
                ≈ ¥{{ formatPayAmount(scope.row.pay, scope.row.rate) }}
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="time" label="交易时间" width="170">
          <template #default="scope">
            <div class="time-info">
              <div class="time-date">{{ formatDate(scope.row.time) }}</div>
              <div class="time-hour">{{ formatTime(scope.row.time) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" text @click="viewOrderDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredOrders.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="showOrderDetail" 
      title="订单详情" 
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">订单基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">订单号：</span>
                <span class="value">{{ selectedOrder.id }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">订单状态：</span>
                <el-tag :type="getOrderStatusType(selectedOrder.status)" size="small">
                  {{ selectedOrder.status || '已完成' }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">交易时间：</span>
                <span class="value">{{ formatDateTime(selectedOrder.time) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="label">结算汇率：</span>
                <span class="value">{{ selectedOrder.rate }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 商品信息 -->
        <div class="detail-section">
          <h3 class="section-title">商品信息</h3>
          <div class="product-detail">
            <div class="product-name">{{ selectedOrder.name }}</div>
            <div class="product-meta">
              <span>数量：{{ selectedOrder.count }}</span>
              <span>单价：{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.price }}</span>
            </div>
          </div>
        </div>

        <!-- 费用明细 -->
        <div class="detail-section">
          <h3 class="section-title">费用明细</h3>
          <div class="fee-detail-list">
            <div class="fee-item">
              <span class="fee-label">商品总价：</span>
              <span class="fee-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ (selectedOrder.price * selectedOrder.count).toFixed(2) }}</span>
            </div>
            <div class="fee-item">
              <span class="fee-label">手续费：</span>
              <span class="fee-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.fee }}</span>
            </div>
            <div class="fee-item">
              <span class="fee-label">附加费：</span>
              <span class="fee-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.extra }}</span>
            </div>
            <div class="fee-item">
              <span class="fee-label">运费补差：</span>
              <span class="fee-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.freight }}</span>
            </div>
            <div class="fee-item total">
              <span class="fee-label">小计：</span>
              <span class="fee-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ getSubtotal(selectedOrder) }}</span>
            </div>
          </div>
        </div>

        <!-- 优惠信息 -->
        <div class="detail-section" v-if="selectedOrder.coupon || selectedOrder.point">
          <h3 class="section-title">优惠信息</h3>
          <div class="discount-detail-list">
            <div class="discount-item" v-if="selectedOrder.coupon">
              <el-tag type="success" size="small">优惠券</el-tag>
              <span class="discount-value">-{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.coupon }}</span>
            </div>
            <div class="discount-item" v-if="selectedOrder.point">
              <el-tag type="warning" size="small">积分抵扣</el-tag>
              <span class="discount-value">-{{ getCurrencySymbol(selectedOrder.currency) }}{{ selectedOrder.point }}</span>
            </div>
            <div class="discount-item total">
              <span class="discount-label">优惠总计：</span>
              <span class="discount-value">-{{ getCurrencySymbol(selectedOrder.currency) }}{{ getTotalDiscount(selectedOrder) }}</span>
            </div>
          </div>
        </div>

        <!-- 实付金额 -->
        <div class="detail-section">
          <h3 class="section-title">实付金额</h3>
          <div class="final-amount">
            <div class="final-amount-main">
              <span class="amount-label">最终支付：</span>
              <span class="amount-value">{{ getCurrencySymbol(selectedOrder.currency) }}{{ formatPayAmount(selectedOrder.pay) }}</span>
            </div>
            <div class="final-amount-sub" v-if="selectedOrder.currency === 'JPY'">
              <span class="amount-label">人民币：</span>
              <span class="amount-value">≈ ¥{{ formatPayAmount(selectedOrder.pay, selectedOrder.rate) }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showOrderDetail = false">关闭</el-button>
          <el-button type="primary" @click="printOrderDetail">打印订单</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, computed } from 'vue';
import { 
  ShoppingCart, 
  Money, 
  Discount, 
  TrendCharts, 
  Search, 
  Download 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps<{ orders: any[] }>();

// 响应式数据
const searchKeyword = ref('');
const timeRange = ref('');
const orderStatus = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const showOrderDetail = ref(false);
const selectedOrder = ref<any>(null);

// 计算属性
const totalOrders = computed(() => props.orders.length);

const totalAmount = computed(() => {
  return props.orders.reduce((sum, order) => {
    return sum + parseFloat(order.pay || 0);
  }, 0).toFixed(2);
});

const totalDiscount = computed(() => {
  return props.orders.reduce((sum, order) => {
    const coupon = parseFloat(order.coupon || 0);
    const point = parseFloat(order.point || 0);
    return sum + coupon + point;
  }, 0).toFixed(2);
});

// 获取主要货币类型
const primaryCurrency = computed(() => {
  const currencies = props.orders.map(order => order.currency).filter(Boolean);
  return currencies.length > 0 ? currencies[0] : 'CNY';
});

const averageOrder = computed(() => {
  if (props.orders.length === 0) return '0.00';
  return (parseFloat(totalAmount.value) / props.orders.length).toFixed(2);
});

const filteredOrders = computed(() => {
  let filtered = props.orders;
  
  // 搜索过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(order => 
      order.id.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      order.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const days = parseInt(timeRange.value);
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);
    
    filtered = filtered.filter(order => {
      const orderDate = new Date(order.time);
      return orderDate >= cutoffDate;
    });
  }
  
  return filtered;
});

// 方法
function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

function formatTime(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
}

function exportOrders() {
  ElMessage.success('导出功能开发中...');
}

function viewOrderDetail(order: any) {
  selectedOrder.value = order;
  showOrderDetail.value = true;
}

function handleCloseDetail() {
  showOrderDetail.value = false;
  selectedOrder.value = null;
}

function getOrderStatusType(status: string) {
  switch (status) {
    case 'completed':
      return 'success';
    case 'processing':
      return 'warning';
    case 'cancelled':
      return 'danger';
    default:
      return 'success';
  }
}

function formatDateTime(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
}

function getSubtotal(order: any) {
  const basePrice = order.price * order.count;
  const fee = parseFloat(order.fee || 0);
  const extra = parseFloat(order.extra || 0);
  const freight = parseFloat(order.freight || 0);
  return (basePrice + fee + extra + freight).toFixed(2);
}

function getTotalDiscount(order: any) {
  const coupon = parseFloat(order.coupon || 0);
  const point = parseFloat(order.point || 0);
  return (coupon + point).toFixed(2);
}

function printOrderDetail() {
  ElMessage.success('打印功能开发中...');
}

function formatPayAmount(amount: string | number, rate?: string | number) {
  // 如果金额包含斜杠，取第一个值
  if (typeof amount === 'string' && amount.includes('/')) {
    amount = amount.split('/')[0];
  }
  
  const numAmount = parseFloat(amount as string);
  
  if (rate) {
    const numRate = parseFloat(rate as string);
    return (numAmount * numRate).toFixed(0);
  }
  
  return numAmount.toFixed(0);
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;
}

function handleCurrentChange(page: number) {
  currentPage.value = page;
}

function getCurrencySymbol(currency: string) {
  switch (currency?.toUpperCase()) {
    case 'JPY':
      return '¥';
    case 'CNY':
      return '¥';
    case 'USD':
      return '$';
    case 'EUR':
      return '€';
    default:
      return '¥';
  }
}
</script>

<style scoped>
.order-tab {
  padding: 20px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.stat-card:nth-child(4) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.9;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 订单列表样式 */
.orders-section {
  margin-bottom: 20px;
}

.order-row:hover {
  background-color: #f0f9ff !important;
}

.order-id {
  display: flex;
  align-items: center;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-weight: 500;
  color: #303133;
}

.product-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.quantity, .price {
  display: flex;
  align-items: center;
}

.fee-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.fee-row {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.fee-label {
  color: #909399;
}

.fee-value {
  color: #606266;
  font-weight: 500;
}

.discount-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.discount-row {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.discount-value {
  color: #67c23a;
  font-weight: 500;
}

.rate-value {
  color: #409eff;
  font-weight: 500;
}

.pay-amount {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.amount-main {
  font-size: 16px;
  font-weight: bold;
  color: #e6a23c;
  line-height: 1.2;
}

.amount-sub {
  font-size: 11px;
  color: #909399;
  line-height: 1;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-date {
  font-size: 12px;
  color: #606266;
}

.time-hour {
  font-size: 11px;
  color: #909399;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 订单详情对话框样式 */
.order-detail {
  padding: 0;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.detail-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.detail-item .value {
  color: #303133;
  font-weight: 500;
}

.product-detail {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.product-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #606266;
}

.fee-detail-list {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid #e4e7ed;
}

.fee-item:last-child {
  border-bottom: none;
}

.fee-item.total {
  font-weight: 600;
  color: #303133;
  border-top: 2px solid #409eff;
  padding-top: 8px;
  margin-top: 8px;
}

.fee-label {
  color: #606266;
}

.fee-value {
  color: #303133;
  font-weight: 500;
}

.discount-detail-list {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.discount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  gap: 8px;
}

.discount-item.total {
  font-weight: 600;
  color: #303133;
  border-top: 2px solid #67c23a;
  padding-top: 8px;
  margin-top: 8px;
}

.discount-label {
  color: #606266;
}

.discount-value {
  color: #67c23a;
  font-weight: 500;
}

.final-amount {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 12px;
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.final-amount-main {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.final-amount-sub {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  opacity: 0.8;
  font-size: 14px;
}

.amount-label {
  font-size: 16px;
  opacity: 0.9;
}

.amount-value {
  font-size: 24px;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
}
</style> 